package com.zzyl.framework.interceptor;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MemberInterceptor implements HandlerInterceptor {


    @Autowired

    private TokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是Controller层的请求，直接放行
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = request.getHeader("authorization");
        if (StrUtil.isEmpty(token)) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            AjaxResult ajax = AjaxResult.error(401, "请重新登录");

            response.getWriter().write(JSONUtil.toJsonStr(ajax));
            return false;
        }

        Claims claims = tokenService.parseToken(token);
        Long userId = Long.parseLong(claims.getSubject());
        if (userId == null) {
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            AjaxResult ajax = AjaxResult.error(401, "请重新登录");

            response.getWriter().write(JSONUtil.toJsonStr(ajax));
            return false;
        }

        UserThreadLocal.set(userId);

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
